/**
 * 事件派发类
 */
export default class EventMgr {

    private static _ins: EventMgr;

    public static get ins(): EventMgr {
        if (!this._ins) {
            this._ins = new EventMgr()
        }
        return this._ins;
    }

    private events: Map<string, EventData[]> = new Map();

    public on(eventId: string, listen: Function, caller: any) {
        if (!this.events.get(eventId)) {
            this.events.set(eventId, []);
        }
        let list = this.events.get(eventId);
        for (let e of list) {
            if (e.eventId == eventId && e.caller == caller && e.func == listen) {
                //已有一样的监听
                return;
            }
        }
        let e: EventData = {
            eventId: eventId,
            func: listen,
            caller: caller,
            once: false,
            doRemove: false
        }
        list.push(e);
    }

    public event(eventId: string, param?: any) {
        let list = this.events.get(eventId);
        if (!list) return;
        for (let e of list) {
            e.func.apply(e.caller, [param]);
            if (e.once) {
                e.doRemove = true;
            }
        }
    }

    public off(eventId: string, listen: Function, caller: any) {
        if (!this.events.get(eventId)) {
            return;
        }
        let list = this.events.get(eventId);
        for (let i = 0; i < list.length; i++) {
            let e = list[i]
            if (e.eventId == eventId && e.caller == caller && e.func == listen) {
                //一样的监听
                list.splice(i, 1);
                return;
            }
        }
    }
}

export class EventData {
    eventId: string;
    func: Function;
    caller: any;
    once: boolean;
    doRemove: boolean;
}